/**
 * 常用方法封装 请求，文件上传等
 * @author echo. 
 **/
import {
	json_replace
} from '@/utils/replace.js';
import md5 from '@/node_modules/js-md5/src/md5.js';
const yiyu = {
	//接口地址
	interfaceUrl: function() {
		return 'http://www.rutss.xyz'
	},
	toast: function(text, duration, success) {
		uni.showToast({
			title: text || 'Fails',
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},

	modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
		uni.showModal({
			title: title || '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: "#555",
			confirmColor: confirmColor || "#5677fc",
			confirmText: confirmText || "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	/* 缓存默认地址 */
	setAddressId(data) {
		uni.setStorageSync("yyui_key_address", data)
	},
	getAddressId() {
		return uni.getStorageSync("yyui_key_address")
	},
	getUrl() {
		let baseUlr = 'http://www.rutss.xyz/'
		return baseUlr;
	},
	isAndroid: function() {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() == "android"
	},
	isPhoneX: function() {
		const res = uni.getSystemInfoSync();
		let iphonex = false;
		let models = ['iphonex', 'iphonexr', 'iphonexsmax', 'iphone11', 'iphone11pro', 'iphone11promax']
		const model = res.model.replace(/\s/g, "").toLowerCase()
		if (models.includes(model)) {
			iphonex = true;
		}
		return iphonex;
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	delayed: null,
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request: function(url, method, postData, isDelay, isForm, hideLoading, action) {
		//接口请求
		let loadding = false;

		yiyu.delayed && uni.hideLoading();
		clearTimeout(yiyu.delayed);
		yiyu.delayed = null;
		if (!hideLoading) {
			yiyu.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: 'loading...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}
		postData.time_stamp = yiyu.timest();
		postData.method = action;

		let keys = yiyu.getToken() ? yiyu.getKey() : action;
		if (action == 'checkOrderPay' || action == 'weChatPublicLogin' || action == 'authAddress') {
			keys = action;
		}
		postData.sign = yiyu.getSign(postData, keys);
		/* 公共参数 */
		return new Promise((resolve, reject) => {
			uni.request({
				url: url,
				data: postData,
				header: {
					'content-type': false ? 'application/x-www-form-urlencoded' :
						'application/json',
					'Token': yiyu.getToken()
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					clearTimeout(yiyu.delayed)
					yiyu.delayed = null;
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					if (res.data.code != 200) {
						res.data = json_replace(url, res.data);
						this.toast(res.data.message);
					}
					res.data = json_replace(url, res.data);
					resolve(res.data);
				},
				fail: (res) => {
					clearTimeout(yiyu.delayed)
					yiyu.delayed = null;
					yiyu.toast(this.$t('try-again-later'))
					reject(res)
				}
			})
		})
	},

	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(url, postData, files, action) {
		uni.showLoading({
			title: 'Loading'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: url,
				filePath: files,
				name: 'imageFile',
				header: {
					'X-Token': yiyu.getToken()
				},
				formData: postData,
				success: function(res) {
					uni.hideLoading()
					res.data = JSON.parse(res.data)
					res.data = json_replace(url, res.data);
					resolve(res.data);
				},
				fail: function(res) {
					reject(res)
					this.toast(res.msg);
				}
			})
		})
	},
	getWxOpenId: function() { //获取微信openid
		return uni.getStorageSync("wx_openid");
	},
	setWxOpenId: function($openId) { //设置微信openid
		uni.setStorageSync("wx_openid", $openId);
	},

	setWallet(data) {
		uni.setStorageSync("yy_wallet", data)
	},
	getWallet() {

		return uni.getStorageSync("yy_wallet")
	},

	yiyuJsonp: function(url, callback, callbackname) {
		// #ifdef H5
		window[callbackname] = callback;
		let yiyuScript = document.createElement("script");
		yiyuScript.src = url;
		yiyuScript.type = "text/javascript";
		document.head.appendChild(yiyuScript);
		document.head.removeChild(yiyuScript);
		// #endif
	},
	//设置用户信息
	setUserInfo: function(mobile, token, key) {
		uni.setStorageSync("yyui_token", token)
		uni.setStorageSync("yyui_key", key)
		uni.setStorageSync("yyui_mobile", mobile)
	},
	//设置用户信息
	setUserInfoData: function(data) {
		uni.setStorageSync("yyui_user_data", data)
	},
	getUserInfoData: function() {
		return uni.getStorageSync("yyui_user_data")
	},
	/* 用户缓存是否从拼团分享过来的信息 */
	setSharePintuan(data) {
		uni.setStorageSync("yyui_pintuan", data)
	},
	getSharePintuan() {

		return uni.getStorageSync("yyui_pintuan")
	},
	getAlAuto: function() {
		return uni.getStorageSync("yyui_ali_data")
	},
	setUserRefereeData: function(shareid) {
		uni.setStorageSync("yyui_sharecode", shareid)
	},
	getUserReferee: function() {
		return uni.getStorageSync("yyui_sharecode")
	},
	setUserNodeData: function(shareid) {
		uni.setStorageSync("yyui_node", shareid)
	},
	getUserNode: function() {
		return uni.getStorageSync("yyui_node")
	},
	setUserPostionData: function(position) {
		uni.setStorageSync("yyui_position", position)
	},
	getUserPosition: function() {
		return uni.getStorageSync("yyui_position")
	},
	setSign: function(sign) {
		uni.setStorageSync("yyui_sign", sign)
	},
	getSign: function() {
		return uni.getStorageSync("yyui_sign")
	},
	//写入用户小程序头像信息
	setAlAuto(data) {
		uni.setStorageSync("yyui_ali_data", data)
	},
	getAliAutophone: function() {
		return uni.getStorageSync("yyui_ali_data_phone")
	},
	/* 二维码缓存信息 */
	setImgs(data) {
		uni.setStorageSync("yyui_imgs", data)
	},
	getImgs() {
		return uni.getStorageSync("yyui_imgs")
	},
	//写入用户小程序手机号码信息
	setWxAutophone(data) {
		uni.setStorageSync("yyui_wx_data_phone", data)
	},
	//获取token
	getToken() {
		return uni.getStorageSync("yyui_token")
	},
	setToken(token) {
		uni.setStorageSync("yyui_token", token)
	},
	getProvider() {
		return uni.getStorageSync("yyui_provider")
	},
	setProvider(provider) {
		uni.setStorageSync("yyui_provider", provider)
	},
	setReferee(data) {
		uni.setStorageSync("yyui_referee_data", data)
	},
	getReferee() {
		return uni.getStorageSync("yyui_referee_data")
	},
	//获取key
	getKey() {
		return uni.getStorageSync("yyui_key")
	},
	setWechatJson(data) {
		uni.setStorageSync("yyui_wechat_data", data)
	},
	getWechatJson() {
		return uni.getStorageSync("yyui_wechat_data")
	},
	/* 携带参数跳转 */
	getUrlPar() {
		return uni.getStorageSync("yyui_url_par")
	},
	setUrlPar(data) {
		return uni.setStorageSync("yyui_url_par", data)
	},
	/* 设置默认第三方收货地址 */
	setDefalutAddress(data) {
		uni.setStorageSync("yyui_address_defalut", data)
	},
	/* 设置默认第三方收货地址 */
	getDefalutAddress() {
		return uni.getStorageSync("yyui_address_defalut")
	},
	//判断是否登录
	isLogin: function() {
		return uni.getStorageSync("yyui_token") ? true : false
	},
	//跳转登录页面
	haslogin: function(shareid) {
		if (yiyu.getToken()) {
			return;
		}
		uni.switchTab({
			url: '/pages/index/index'
		})
	},


	//退出登录
	logout: function() {
		uni.setStorageSync("yyui_token", '')
		uni.setStorageSync("yy_wallet", '') 
	},
	//跳转个人中心
	hrefTo() {
		if (yiyu.getToken()) {
			uni.switchTab({
				url: '/pages/my/my'
			})
		}

	},
	//跳转页面，校验登录状态
	href(url, isVerify) {
		if (isVerify && !yiyu.isLogin()) {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		} else {
			uni.navigateTo({
				url: url
			});
		}
	},

	timest: function() {
		var tmp = Date.parse(new Date()).toString();
		tmp = tmp.substr(0, 10);
		return tmp;
	},

	getSign: function(params, kAppSecret) {
		if (typeof params == "string") {
			return yiyu.paramsStrSort(params, kAppSecret);
		} else if (typeof params == "object") {
			var arr = [];
			for (var i in params) {
				if (i != 'sign') {
					if (params[i] != '') {
						arr.push((i + "=" + params[i]));
					}

				}
			}

			return yiyu.paramsStrSort(arr.join(("&")), kAppSecret);
		}
	},
	/* 隐藏字符串 */
	hidden: function(str, frontLen, endLen) {
		//str：要进行隐藏的变量  frontLen: 前面需要保留几位    endLen: 后面需要保留几位
		var len = str.length - frontLen - endLen;
		var xing = "";
		for (var i = 0; i < len; i++) {
			xing += "***";
		}
		return (
			str.substring(0, frontLen) + "***" + str.substring(str.length - endLen)
		);
	},
	paramsStrSort: function(paramsStr, kAppSecret) {

		var str = paramsStr.split("&").sort().join("&");
		var sign = md5(str + kAppSecret);
		return sign.toUpperCase();
	}
}

export default yiyu